package com.naiterui.ehp.bs.esign.api.netrain.service;

import com.naiterui.ehp.bp.constants.EsignServiceProviderEnum;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bs.esign.api.ISignService;
import com.naiterui.ehp.bs.esign.api.netrain.utils.NetrainPdfSignUtil;
import com.naiterui.ehp.bs.esign.api.netrain.utils.SealImageUtil;
import com.naiterui.ehp.bs.esign.api.vo.SignAccountVO;
import com.naiterui.ehp.bs.esign.api.vo.SignCallbackVO;
import com.naiterui.ehp.bs.esign.api.vo.SignFileParamVO;
import com.naiterui.ehp.bs.esign.api.vo.SignUserInfoVO;
import com.naiterui.ehp.bs.esign.api.vo.UserInfoParamVO;
import com.naiterui.ehp.bs.esign.exception.ExceptionCodes;
import com.naiterui.ehp.bs.esign.service.IEsignService;
import com.naiterui.ehp.bs.esign.vo.esign.PreSignResultVO;
import java.awt.Color;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author guoyongxiang
 * @date 2020/1/13 20:31
 * @since 1.0.0
 */
@Slf4j
public class SignServiceImpl implements ISignService {

    @Value("${file.base.prefix}")
    private String basePath;

    @Override
    public EsignServiceProviderEnum getCurrentServiceProvider() {
        return EsignServiceProviderEnum.NETRAIN;
    }

    @Override
    public SignUserInfoVO registAccount(UserInfoParamVO userInfoParamVO) throws BusinessException {
        String accountId = MD5.md5(userInfoParamVO.getIdNo());
        String sealData = null;
        if (userInfoParamVO.isSealFlag()) {
            sealData = this.createSeal(accountId, userInfoParamVO.getName(),null);
        }
        return SignUserInfoVO.builder()
            .openId(accountId)
                             .sealData(sealData)
                             .callbackType(SignUserInfoVO.TYPE_CALLBACK_INTERFACE)
                             .build();
    }

    @Override
    public void deleteAccount(String accountId) throws BusinessException {
        log.info("删除签名账号：accountId={}", accountId);
    }

    @Override
    public SignUserInfoVO updateAccount(UserInfoParamVO userInfoParamVO) throws BusinessException {
        return this.registAccount(userInfoParamVO);
    }

    @Override
    public String getRealnameCode(String name, String phone, String idCard) throws BusinessException {
        return UUID.randomUUID().toString();
    }

    @Override
    public boolean checkRealnameCode(String phone, String code) throws BusinessException {
        return true;
    }

    @Override
    public String createSeal(String accountId, String name, String typeface) throws BusinessException {
        String path = "/tmp/" + UUID.randomUUID() + ".png";
        try {
            boolean result = SealImageUtil.nameSealGeneration(name, path, Color.BLACK, typeface);
            if(result){
                byte[] b = Files.readAllBytes(Paths.get(path));
                return Base64.getEncoder().encodeToString(b);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("生成电子签名签章图异常 accountId:{}, name:{}", accountId, name, e);
            throw new BusinessException(ExceptionCodes.FAILED, "生成姓名签章图片异常");
        }
    }

    @Override
    public PreSignResultVO preSign(SignFileParamVO signParamVO, SignAccountVO signAccountVO) throws BusinessException {
        PreSignResultVO resultVO = new PreSignResultVO();
        switch (signAccountVO.getRequestFrom()){
            case SignAccountVO.REQUEST_FROM_CMS:
                resultVO.setUniqueId(UUID.randomUUID().toString());
                break;

            case SignAccountVO.REQUEST_FROM_APP:
                throw new BusinessException(ExceptionCodes.PARAM_ERROR, "暂不支持人脸认证");

            default:
                resultVO.setUniqueId(UUID.randomUUID().toString());
                break;
        }
        return resultVO;
    }

    @Override
    public void sign(SignFileParamVO signParamVO, SignAccountVO signAccountVO, IEsignService callback) throws BusinessException {


        String signedPdfBase64 = NetrainPdfSignUtil.pdfSign(signAccountVO.getUserType(), basePath + signAccountVO.getXingkaiSealImage(), signParamVO.getPdfPath(), signParamVO.getOutputPath(),
                basePath + signAccountVO.getSealImage(),
                (int)(float)signParamVO.getX(),
                (int)(float)signParamVO.getY());

        callback.signResult(SignCallbackVO.builder()
            .openId(signAccountVO.getOpenId())
            .urId(signParamVO.getUrId())
            .signedPdfBase64(signedPdfBase64)
            .status(SignCallbackVO.STATUS_SIGNED)
            .uniqueId(signParamVO.getUnionId())
            .signTime(new Date())
            .sealImage(signAccountVO.getSealImage())
            .build());

    }

    @Override
    public void resetSignPwd(String openId, String newPassword) {
        log.info("厂商目前不支持");
    }

}
